package com.youxin.busfoundation.utils.weixin;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URLEncoder;
import java.util.*;
import java.security.MessageDigest;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.youxin.busfoundation.Consts;
import com.youxin.foundation.utils.Md5Utils;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class WXPayUtil {

    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
            WXPayUtil.getLogger().warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }


    /**
     * 生成带有 sign 的 XML 格式字符串
     *
     * @param data Map类型数据
     * @param key API密钥
     * @return 含有sign字段的XML
     */
    public static String generateSignedXml(final Map<String, String> data, String key) throws Exception {
        return generateSignedXml(data, key);
    }





    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }


    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }


    /**
     * 日志
     * @return
     */
    public static Logger getLogger() {
        Logger logger = LoggerFactory.getLogger("wxpay java sdk");
        return logger;
    }

    /**
     * 获取当前时间戳，单位秒
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis()/1000;
    }

    /**
     * 获取当前时间戳，单位毫秒
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }

    /**
     * 生成 uuid， 即用来标识一笔单，也用做 nonce_str
     * @return
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    public static boolean isSignatureValid(Map<String, String> data, String key) throws Exception {
      	 if (!data.containsKey(Consts.FIELD_SIGN) ) {
               return false;
           }
           String sign = data.get(Consts.FIELD_SIGN);
           return generateSignature(data, key).equals(sign);
      }
       /**
        * 生成签名
        *
        * @param data 待签名数据
        * @param key API密钥
        * @return 签名
        */
       public static String generateSignature(final Map<String, String> data, String key) throws Exception {
       	 Set<String> keySet = data.keySet();
            String[] keyArray = keySet.toArray(new String[keySet.size()]);
            Arrays.sort(keyArray);
            StringBuilder sb = new StringBuilder();
            for (String k : keyArray) {
                if (k.equals(Consts.FIELD_SIGN)) {
                    continue;
                }
                if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                    sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
            sb.append("key=").append(key);
            return Md5Utils.MD5(sb.toString()).toUpperCase();
       }
       
       /**
        * 生成签名
        *
        * @param data 待签名数据
        * @param key API密钥
        * @return 签名
        */
       public static String generateSignature2(final Map<String, String> data) throws Exception {
    	   StringBuilder sb = new StringBuilder();
    	   try {
    		   Set<String> keySet = data.keySet();
    		   String[] keyArray = keySet.toArray(new String[keySet.size()]);
    		   Arrays.sort(keyArray);
    		   for (String k : keyArray) {
    			   if (k.equals(Consts.FIELD_SIGN)) {
    				   continue;
    			   }
    			   if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
    				   sb.append(k).append("=").append(URLEncoder.encode(data.get(k).trim())).append("&");
    		   }
			} catch (Exception e) {
				// TODO: handle exception
			}
    	   return sb.toString();
       }
       
       /**
        * 处理 HTTPS API返回数据，转换成Map对象。return_code为SUCCESS时，验证签名。
        * @param xmlStr API返回的XML格式数据
        * @return Map类型数据
        * @throws Exception
        */
       public static Map<String, String> processResponseXml(String xmlStr,String apiKey) throws Exception {
           String RETURN_CODE = "return_code";
           String return_code;
           Map<String, String> respData = WXPayUtil.xmlToMap(xmlStr);
           if (respData.containsKey(RETURN_CODE)) {
               return_code = respData.get(RETURN_CODE);
           }
           else {
               throw new Exception(String.format("No `return_code` in XML: %s", xmlStr));
           }

           if (return_code.equals(Consts.FAIL_CAPITAL)) {
               return respData;
           }
           else if (return_code.equals(Consts.SUCCESS_CAPITAL)) {
           	boolean rs = WXPayUtil.isSignatureValid(respData, apiKey);
              if (rs) {
                  return respData;
              }
              else {
                  throw new Exception(String.format("Invalid sign value in XML: %s", xmlStr));
              }
           }
           else {
               throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, xmlStr));
           }
       }
}
